﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.RoleCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using System.Data;

namespace RBAC_Uthorization.API.Application.CommandHandlers.RoleHandler
{
    public class RoleCreateCommandHandlers : IRequestHandler<RoleCreateCommand, ApiResult<int>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<RoleCreateCommandHandlers> _logger;
        private readonly IMapper _mapper;

        public RoleCreateCommandHandlers(IRoleRepository roleRepository, ILogger<RoleCreateCommandHandlers> logger, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(RoleCreateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                
                var roles = await _roleRepository.GetAllAsync();
                if (roles.Any(x => x.name == request.dto.name && x.offic_id == request.offic_id && x.del_flag == 0))
                {
                    return new ApiResult<int>() { Code = ResultCode.BadRequest,Message="角色名称已存在" };
                }

                var entity = _mapper.Map<sys_role>(request.dto);
                entity.offic_id = request.offic_id;
                entity.create_date = DateTime.UtcNow;
                entity.create_by = request.createName;
                entity.sys_id = request.sys_id;

                var addResult = await _roleRepository.AddAsync(entity);
                if (addResult > 0)
                {
                    _logger.LogInformation($"创建人:{request.createName},角色： {entity.name},系统：{request.sys_id} 添加成功 ");
                    return new ApiResult<int>();
                }
                else
                {
                    _logger.LogError($"创建人：{request.createName}系统：{request.sys_id} 角色添加失败");
                    return new ApiResult<int>(ResultCode.Fail, "角色添加失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "角色添加异常");
                return new ApiResult<int>(ResultCode.Fail, "角色添加异常");
            }
        }
    }
}
